package cxy.highConcurrency;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo<K, V> {
	private final Map<K, V> m = new HashMap<>();
	
	private final ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	private final Lock readLock = rwl.readLock();
	
	private final Lock writeLock = rwl.writeLock();
	
	V get(K key) {
		V v = null;
		//读缓存
		readLock.lock();
		try {
			v = m.get(key);
		} finally {
			readLock.unlock();
		}
		//缓存中存在，直接返回
		if (v != null) {
			return v;
		}
		//缓存不存在，查询数据库
		writeLock.lock();
		try {
			//再次验证为null，提升性能
			v = m.get(key);
			if (v == null) {
				//查询数据库
				m.put(key, v);
			}
		} finally {
			writeLock.unlock();
		}
		return v;
		
	}
	
	
}
